package org.nf.trading.service.app.order.impl;


import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.nf.trading.config.RabbitConfig;
import org.nf.trading.dao.OrderMapper;
import org.nf.trading.dao.ProductMapper;
import org.nf.trading.entity.Order;
import org.nf.trading.exception.app.order.OrderDataException;
import org.nf.trading.exception.app.product.ProductDataException;
import org.nf.trading.service.app.order.OrderService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
@RequiredArgsConstructor
@Transactional
public class OrderServiceImpl implements OrderService {
    private final OrderMapper orderMapper;

    private final RabbitTemplate rabbitTemplate;

    private final RedisTemplate<String, Object> redisTemplate;

    private final ProductMapper productMapper;


    /**
     * 通过卖家id查询所有订单
     * @param sellerId
     * @return
     */
    @Override
    public List<Order> listOrdersBySeller(Integer sellerId) {
        if (sellerId == null){
            throw new OrderDataException(500,"商家id不能为空");
        }
        return orderMapper.listOrdersBySeller(sellerId);
    }

    @Override
    public List<Order> listOrdersByUid(Integer uid) {
        if (uid == null){
            throw new OrderDataException(500,"用户id不能为空");
        }
        return orderMapper.listOrdersByUid(uid);
    }

    /**
     * 通过订单id修改状态
     * @param orderId
     * @param status
     * @return
     */
    @Override
    public boolean updateOrderStatus(Integer orderId, Integer status) {
        if (orderId == null || status == null){
            log.error("订单id和状态不能为空");
            throw new OrderDataException(500,"订单id和状态不能为空");
        }
        return orderMapper.updateOrderStatus(orderId, status) == 1;
    }

    /**
     * 通过订单id和买家id查询订单
     * @param orderId
     * @return
     */
    @Override
    public Order getOrderIdAndUid(Integer orderId) {
        if (orderId == null){
            throw new OrderDataException(500,"订单ID或买家ID不能为空");
        }
        return orderMapper.getOrderIdAndUid(orderId);
    }

    /**
     * 通过状态查询全部订单
     *
     * @param statue
     * @return
     */
    @Override
    public List<Order> listOrdersByStatue(Integer buyerId, Integer statue) {
        if (statue == null || buyerId == null) {
            log.error("参数为空");
            throw new OrderDataException(500, "参数为空");
        }
        return orderMapper.listOrdersByStatue(buyerId, statue);
    }

    /**
     * 添加订单
     *
     * @param order
     * @return
     */
    @Override
    public int addOrder(Order order) {
        System.out.println("订单："+order);
        if (order == null) {
            throw new OrderDataException(500, "参数为空");
        }
        //生成订单
        boolean result = orderMapper.insert(order) == 1;

        //减库存
        int stockResult = productMapper.minusStock(order.getProductId(), order.getProductCount());

        //判断库存是否不足
        if (stockResult == 0){
            throw new ProductDataException(500, "库存不足");
        }

        //是否是未支付状态，是则将设置订单过期时间
//        if (order.getOrderStatus() == 0) {
//            log.info("状态为0");
//            redisTemplate.opsForValue().set("orderDate:" + order.getOrderId(), order.getOrderId(), 1, TimeUnit.MINUTES);
//        }

        //添加到队列
        //创建消息的唯一ID
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(order.getOrderId() + "");
        //发送消息
        rabbitTemplate.convertAndSend(RabbitConfig.DELAY_EXCHANGE_NAME, RabbitConfig.DELAY_ROUTER_KEY, order,
                //通过消息的后置处理器设置延迟放入的时间
                messagePostProcessor -> {
                    messagePostProcessor.getMessageProperties().setDelay(1000 * 60 * 3);
                    return messagePostProcessor;
                }, correlationData);
        return order.getOrderId();
    }

    /**
     * 查询全部订单
     * @return
     */
    @Override
    public List<Order> selectAll() {
        return orderMapper.selectAll();
    }

    @Override
    public boolean deleteOrder(Integer orderId) {
        if (orderId == null){
            log.error("订单id为空");
            throw new OrderDataException(500,"参数为空");
        }
        return orderMapper.deleteByPrimaryKey(orderId) == 1;
    }

    @Override
    public PageInfo<Order> selectOrderAll(Integer pageNum, Integer pageSize, Order order) {
        return new PageInfo<>(orderMapper.selectOrderAll(pageNum, pageSize, order));
    }
}
